<?php
/*********************************************************
author			Henson
date			2013-08-23
function		mysql
*********************************************************/

class Mysql
{
	var $debug = 0;
	var $slave_host = "";
	var $_resource;

	/* 初始化 */
	function __construct( $host=_DB_HOST ,  $user=_DB_USER, $pass=_DB_PASS, $db=_DB_NAME , $encode="utf8")
	{
		$this->connect( $host , $user, $pass, $db , $encode );
	}

	function error($msg='')
	{
		//写错误日志
		$time = date("Y-m-d H:i:s");
		$path = dirname(dirname(__FILE__))."/log/".substr($time , 0 , 7);
		if(!is_dir($path))
			@mkdir($path);
		$logFile = "${path}/".substr($time , 8 , 2)."_mysql_error.txt";

		$info = $time ;
		if($msg)
		{
			$info .= "\t" . $msg ;
		}
		else
		{
			$info .= "\t" . $_SERVER['PHP_SELF'] . "\t" .mysql_errno()."\t".mysql_error()."\r\n";
		}
		$fp = @fopen($logFile,"a+");
		@fwrite($fp,$info);
		@fclose($fp);
	}

	function close()
	{
	    @mysql_close($this->_resource);
	}
	
	/* 连接数据库  */
	function connect( $host , $user, $pass, $db='' , $encode="utf8" )
	{
		
		// perform a number of fatality checks, then die gracefully
		if (!function_exists( 'mysql_connect' ))
		{
			$this->error("MySql扩展未载入");
			die ("系统升级中_p");
		}
		if (!($this->_resource = @mysql_connect( $host, $user, $pass )))
		{
			$this->error();
			die( '系统升级中_m' );
		}
		if ($db)
		{
			$this->selectDb( $db );
		}
		if( $encode!='' )
		{
			$version = explode( ".", mysql_get_server_info());
			if( $version[0]>4 || ($version[0]==4&&$version[1]>=1) )
			{
				$q = "set names ".$encode; //echo $q;
				$this->setQuery($q);
				$this->query();
			}
		}
	}


	/* select db  */
	function selectDb( $db )
	{
		if (!mysql_select_db($db,$this->_resource)) 
		{
			$this->error();
			die("系统升级中_d");
		}	    
	} 

	function setQuery( $sql) 
	{
			$sql = trim( $sql );
			$this->_sql = $sql;
	}

	function query($sql="")
	{
		if($sql!="")
			$this->_sql = $sql;

		$this->_cursor = mysql_query( $this->_sql, $this->_resource );
		if (!$this->_cursor)
		{
			$this->error(mysql_error( $this->_resource )." SQL=   $this->_sql  \r\n");
			if($this->debug)
			{
				echo mysql_errno( $this->_resource );
				echo mysql_error( $this->_resource )." SQL=   $this->_sql  ";
			}
			return false;
		}
		return $this->_cursor;
	}

	//返回首条记录的第一个字段
	function loadResult($sql="")
	{
		if (!($cur = $this->query($sql))) {
			return null;
		}
		$ret = null;
		if ($row = mysql_fetch_row( $cur )) {
			$ret = $row[0];
		}
		mysql_free_result( $cur );
		return $ret;
	}

	/**
	* @return The first row of the query.
	*/
	function loadRow( $sql="" , $mode = "assoc" )
	{
		if (!($cur = $this->query($sql))) 
			return null;
		
		$ret = null;
		if( $mode =="object" )return mysql_fetch_object( $cur );
		elseif( $mode =="assoc" )$result_type = MYSQL_ASSOC;
		elseif( $mode =="num" )$result_type = MYSQL_NUM;
		elseif( $mode =="both" )$result_type = MYSQL_BOTH;
		else	return;
		$ret = mysql_fetch_array( $cur , $result_type );
		mysql_free_result( $cur );
		return $ret;
	}

	function loadAssocList( $key="")
	{
	   return $this->loadList( $key , "assoc" );
	}
	

	function loadList( $key='' , $mode="assoc" )
	{
		if (!($cur = $this->query())) {
			return null;
		}
		$array = array();
		if($mode =="object" )
		{
			while ($row = mysql_fetch_object( $cur )) {
				if ($key) {
					$array[$row->$key] = $row;
				} else {
					$array[] = $row;
				}
			}
		}
		else
		{	
			if( $mode =="assoc" )$result_type = MYSQL_ASSOC;
			elseif( $mode =="num" )$result_type = MYSQL_NUM;
			elseif( $mode =="both" )$result_type = MYSQL_BOTH;
			else	return;			
			while ($row = mysql_fetch_array( $cur , $result_type ))
			{
				if ($key) {
					$array[$row[$key]] = $row;
				} else {
					$array[] = $row;
				}
			}
		}

		mysql_free_result( $cur );
		return $array;
	}



	/**
	* Load an array of single field results into an array
	*/
	function loadResultList( $indexKey='0' , $valueKey='' )
	{
		if (!($cur = $this->query())) {
			return null;
		}
		$array = array();
		if ($indexKey && $valueKey)
		{		
			while ($row = mysql_fetch_assoc( $cur ))
			{	
				$array[$row[$indexKey]] = $row[$valueKey];
			}
		}
		else
		{
			while ($row = mysql_fetch_row( $cur ))
			{
				$array[] = $row[$indexKey];
			}
		}
		mysql_free_result( $cur );
		return $array;
	}

	function insertSql( &$row , $table , $e=false )
	{
		foreach ($row as $c=>$v) 
		{
			$carr[]="`" . $c . "`";
			if($e)$v = $this->e($v);
			$varr[]="'" . $v . "'";
		}
		$sql="Insert into $table (" . implode( "," , $carr ) .")Values(". implode( "," , $varr ) .")"; 
		return $sql;
	}

	//插入一条数据
	function insert( &$row , $table , $e=false )
	{
		$sql=$this->insertSql( $row , $table , $e );
		$this->query($sql);
		return mysql_insert_id();
		//echo $sql;
	} 

	//更新一条数据
	function update( &$row , $table , $where , $e=false )
	{
		foreach ($row as $c=>$v) 
		{
			if($e)$v = $this->e($v);
			$carr[]="`" . $c . "` = '" . $v . "'  ";
		}
		$sql="Update $table set " . implode( "," , $carr ) . $where;	//echo $sql;
		$this->setQuery($sql);
		return $this->query();
	} 

	//删除一条数据
	function delete(  $table , $where )
	{
		$sql="Delete From  $table " . $where;	//echo $sql;
		$this->setQuery($sql);
		return $this->query();
	} 

	//代替mysql_escape_string
	function e($v)
	{
		//return mysql_escape_string($v);
		//处理反斜杠
		$v =  str_replace("\r","\\r",$v);
		$v =  str_replace("\n","\\n",$v);
		$v =  str_replace("\'","'",$v);
		$v =  str_replace("'","\'",$v);
		if(substr($v,-1)=="\\")return substr($v,0,-1);
		//prt($v);
		return $v;
	}
	
	function __destruct()
	{
		$this->close();
	}
}//end class

?>